@page "/app/{AppId}/Reporting"
@using Passwordless.Common.Models.Reporting
@using Passwordless.AdminConsole.Components.Pages.App.ReportingComponents;

@inherits BaseApplicationPage

@inject IScopedPasswordlessClient PasswordlessClient
@inject IHttpContextAccessor HttpContextAccessor;

<HeadContent>
    <SecureScript type="text/javascript" src="lib/apexcharts/apexcharts.min.js" />
</HeadContent>

<Page Title="Reporting">
    <TrendingCardsStats class="col-span-2" Items="SummaryItems" />
    <Panel>
        <div class="flex flex-col space-y-4">
            @if (IsFilterDatePickerEnabled)
            {
                <EditForm id="filter-form" class="flex items-end space-x-4" EditContext="_filterContext" FormName="filter-form">
                    <div class="flex-1">
                        <label for="from-datepicker">From</label>
                        <InputDate DisplayName="From" id="from-datepicker" Type="InputDateType.Date" @bind-Value="Filter.From"/>
                    </div>
                    <div class="flex-1">
                        <label for="to-datepicker">To</label>
                        <InputDate DisplayName="To" id="to-datepicker" Type="InputDateType.Date" @bind-Value="Filter.To"/>
                    </div>
                    <button id="filter-btn" class="btn btn-primary flex-1" type="submit">
                        Filter
                    </button>
                </EditForm>
                <hr/>
            }
            <EditForm id="filter-preset-form" EditContext="_filterContext" FormName="filter-preset-form">
                <div class="btn-group-basic">
                    <button type="submit" class="btn-group-basic-item" name="filter-preset-form" value="1w">Last Week</button>
                    <button type="submit" class="btn-group-basic-item" name="filter-preset-form" value="1m">Last Month</button>
                    <button type="submit" class="btn-group-basic-item" name="filter-preset-form" value="6m">Last 6 Months</button>
                    <button type="submit" class="btn-group-basic-item" name="filter-preset-form" value="1y">Last Year</button>
                    <button type="submit" class="btn-group-basic-item" name="filter-preset-form" value="5y">Last 5 Years</button>
                </div>
            </EditForm>
        </div>
        <hr />
        <div class="gap-4 grid grid-cols-1 md:grid-cols-2">
            @if (IsLoaded)
            {
                <TotalCredentialsCountChart Data="PeriodicCredentialReports" />
                <TotalUsersCountChart Data="PeriodicCredentialReports" />
            }
        </div>
    </Panel>
</Page>

@code {
    public bool IsFilterDatePickerEnabled => false;

    [SupplyParameterFromForm] public FilterViewModel? Filter { get; set; }
    
    private EditContext? _filterContext;

    public IEnumerable<PeriodicCredentialReportResponse> PeriodicCredentialReports { get; set; } = new List<PeriodicCredentialReportResponse>(0);
    
    public IEnumerable<PeriodicActiveUserReportResponse> PeriodicActiveUserReports { get; set; } = new List<PeriodicActiveUserReportResponse>(0);

    public ICollection<TrendingCardsStats.Item> SummaryItems { get; set; } = new List<TrendingCardsStats.Item>(0);
    
    public bool IsLoaded { get; private set; }    

    protected override async Task OnInitializedAsync()
    {
        Filter ??= new FilterViewModel();
        _filterContext = new EditContext(Filter);
        if (HttpContextAccessor.HttpContext!.Request.HasFormContentType && HttpContextAccessor.HttpContext.Request.Form["_handler"] != "filter-form")
        {
            switch (HttpContextAccessor.HttpContext.Request.Form["filter-preset-form"])
            {
                case "1w":
                    Filter.From = DateTime.UtcNow.Date.AddDays(-7);
                    break;
                case "1m":
                    Filter.From = DateTime.UtcNow.Date.AddMonths(-1);
                    break;
                case "6m":
                    Filter.From = DateTime.UtcNow.Date.AddMonths(-6);
                    break;
                case "1y":
                    Filter.From = DateTime.UtcNow.Date.AddYears(-1);
                    break;
                case "5y":
                    Filter.From = DateTime.UtcNow.Date.AddYears(-5);
                    break;
            }
            Filter.To = null;
        }
        IsLoaded = await LoadAsync();
    }

    public async Task<bool> LoadAsync()
    {
        var periodicCredentialReportRequest = PeriodicCredentialReportRequest.Create(Filter.From, Filter.To);
        PeriodicCredentialReports = await PasswordlessClient.GetPeriodicCredentialReportsAsync(periodicCredentialReportRequest);
        var periodicActiveUserReportRequest = PeriodicActiveUserReportRequest.Create(Filter.From, Filter.To);
        PeriodicActiveUserReports = await PasswordlessClient.GetPeriodicActiveUserReportsAsync(periodicActiveUserReportRequest);
        var lastActiveUserReport = PeriodicActiveUserReports.LastOrDefault();
        if (lastActiveUserReport != null)
        {
            double totalUsers = lastActiveUserReport.TotalUsers;
            SummaryItems.Add(new TrendingCardsStats.Item("Daily Active Users", lastActiveUserReport.DailyActiveUsers, TrendingCardsStats.ValueTypes.Integer, "({0} of total)", totalUsers == 0 ? 0 : lastActiveUserReport.DailyActiveUsers / totalUsers, TrendingCardsStats.ValueTypes.Percentage));
            SummaryItems.Add(new TrendingCardsStats.Item("Weekly Active Users", lastActiveUserReport.WeeklyActiveUsers, TrendingCardsStats.ValueTypes.Integer, "({0} of total)", totalUsers == 0 ? 0 : lastActiveUserReport.WeeklyActiveUsers / totalUsers, TrendingCardsStats.ValueTypes.Percentage));
        }
        return true;
    }

    public class FilterViewModel
    {
        public DateTime? From { get; set; }
        public DateTime? To { get; set; }
    }
}
